﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace ConsoleApplication1.TestThread
{
    public class FileData
    {
        public  FileStream Stream;
        public int Length;
        public byte[] ByteData;
    }

    public class Thread2
    {
        static void Main()
        {
            ThreadPool.SetMaxThreads(1000, 1000);
            ThreadPoolMessage("start");

            ReadFile();
            Console.ReadKey();
            
        }

        static void CallBack(IAsyncResult result)
        {
            Thread.Sleep(200);
            ThreadPoolMessage("AsyncCallBack");
            FileStream fs = (FileStream)result;
            fs.EndWrite(result);
            fs.Close();


        }

        static void ThreadPoolMessage(string data)
        {
            int a, b;
            ThreadPool.GetAvailableThreads(out a, out b);
            Console.WriteLine(string.Format("{0} CurrentThreadID is:{1}\n "+"WorkThreadId is:{2} CompletionPortThreads is:{3}",data,Thread.CurrentThread.ManagedThreadId,
                a.ToString(),b.ToString()));
        }

        static void ReadFile()
        {
            byte[] byteData = new byte[80961024];
            FileStream fs = new FileStream("file.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite,FileShare.ReadWrite, 1024, true);
            FileData fileData = new FileData();
            fileData.Stream = fs;
            fileData.Length = (int)fs.Length;
            fileData.ByteData = byteData;

            fs.BeginRead(byteData, 0, fileData.Length, new AsyncCallback(Complete), fileData);
        }

        static void  Complete(IAsyncResult result)
        {
            ThreadPoolMessage("Completed");
            FileData fd = (FileData)result.AsyncState;
            int length = fd.Stream.EndRead(result);
            fd.Stream.Close();

            
            if (length != fd.Length)
            {
                throw new Exception("stream is not Complete!");
            }
            string data = Encoding.ASCII.GetString(fd.ByteData, 0, fd.Length);
            Console.Write(data);

        }
    }
}
